const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors')

require("dotenv").config();

app.use(cors());

// 导入路由
const user = require('./routes/userRoute') // 用户
const role = require('./routes/roleRoute') // 角色
const cate = require("./routes/cateRoute") // 宠物分类
const carousel = require("./routes/carouselRoute") // 轮播图
const upload = require("./routes/uploadsRoute") // 上传
const pet = require("./routes/petRoute") // 发布宠物管理
const forum = require("./routes/forumRoute") // 论坛

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(user.routes(), user.allowedMethods())
app.use(role.routes(), role.allowedMethods())
app.use(cate.routes(), cate.allowedMethods())
app.use(carousel.routes(), carousel.allowedMethods())
app.use(upload.routes(), upload.allowedMethods())
app.use(pet.routes(), pet.allowedMethods())
app.use(forum.routes(), forum.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
